package common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;

public final class DICOM2JPEG {

    public static String dicomToJpeg(String from) throws Exception {
        StringBuffer outPath = new StringBuffer("");

        File dicomFile = new File(from);
        if (!dicomFile.exists() || dicomFile.isDirectory()) {
            throw new RuntimeException("Error:文件不存在!");
        }

        BufferedImage myJpegImage = null;
        Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
        ImageReader reader = (ImageReader) iter.next();
        DicomImageReadParam param = null;
        param = (DicomImageReadParam) reader.getDefaultReadParam();
        ImageInputStream iis = ImageIO.createImageInputStream(dicomFile);
        reader.setInput(iis, false);
        myJpegImage = reader.read(0, param);
        iis.close();
        if (myJpegImage == null) {
            throw new RuntimeException("Error:转换图像失败!");
        }

        File jpegFile = new File(dicomFile.getCanonicalPath().replaceAll(".dic", ".jpg"));
        ImageIO.write(myJpegImage, "jpeg", jpegFile);

        outPath.append(jpegFile.getCanonicalPath());
        outPath.append(";");
        return outPath.toString();
    }
}
